# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################

#error handler
error=URL(r=request,f='error')
error_no_text=URL(r=request,f='error_no_text')
error_no_linked_content=URL(r=request,f='error_no_linked_content')

#needed for Picasa
import gdata.photos.service
import gdata.media

def debug():
    return dict(message=BEAUTIFY(request))

@auth.requires_membership('admins')
def index():
    """
    Start page of page module: lets you make new pages
    """
    auth.settings.registration_requires_approval = True
    maxPage=db((db.page.parent==0) & (db.page.language==T.accepted_language)).count()
    form=SQLFORM(db.page)
    form.vars.parent=0
    form.vars.language=T.accepted_language
    form.vars.order_nr=maxPage+1
    if form.process().accepted:
        redirect(URL())
    elif form.errors:
        response.flash = T('form has errors')
    else:
        response.flash = T('please fill the form')
   
    pages=db(db.page.language==T.accepted_language).select()
    return dict(pages=pages, form=form)

@auth.requires_membership('admins')
def deletePageItem():
    try:
        page_id, page_item_id = request.args[:2]
    except:
        redirect(error)
    page=db(db.page.id==page_id).select().first() or redirect(error)
    page_item=db(db.page_item.id==page_item_id).select().first() or redirect(error)
    if page_item.tablename=='page_text':
        del db.page_text[page_item.record_id]
    elif page_item.tablename=='page_image':
        del db.page_image[page_item.record_id]
    elif page_item.tablename=='page_link':
        del db.page_link[page_item.record_id]
    elif page_item.tablename=='page_faq':
        del db.page_faq[page_item.record_id]
    elif page_item.tablename=='page_dealer':
        del db.page_dealer[page_item.record_id]
    elif page_item.tablename=='page_file':
        del db.page_file[page_item.record_id]
    elif page_item.tablename=='page_picasa':
        del db.page_picasa[page_item.record_id]
    elif page_item.tablename=='page_youtube':
        del db.page_youtube[page_item.record_id]
    elif page_item.tablename=='page_slider':
        del db.page_slider[page_item.record_id]
    elif page_item.tablename=='page_form':
        del db.page_form[page_item.record_id]        
    else: 
        #Unknow delete type!
        redirect(error)
    
    #order nummers fatsoenlijk zetten na een delete
    all_page_items = db(db.page_item.page==page_id).select(); 
    deleted_page_item=db(db.page_item.id==page_item_id).select().first() or redirect(error)   
    for page_item in all_page_items:
       if (int(page_item.order_nr) > int(deleted_page_item.order_nr)):
           orderNr = int(page_item.order_nr)-1          
           db((db.page_item.id == page_item.id) & (db.page_item.page==page_id)).update(order_nr = orderNr)
         
    #delete the page_item  
    del db.page_item[page_item_id]
    redirect(URL('showEditable/%s' % page_id))

def makeThumbnail(dbtable,ImageID,size=(134,134)):
    try:    
        thisImage=db(dbtable.id==ImageID).select()[0]
        import os, uuid
        from PIL import Image
    except: return
    im=Image.open(request.folder + 'uploads/' + thisImage.image)
    im.thumbnail(size,Image.ANTIALIAS)
    thumbName='page.imageThumb.%s.png' % (uuid.uuid4())
    im.save(request.folder + 'static/images/thumbs/' + thumbName,'png', optimize=True)
    thisImage.update_record(imageThumb=thumbName)
    return 

@auth.requires_membership('admins')
def sortOrderNr():
    try:
        #ophalen args
        page_id, page_item_id, new_sort_var = request.args[:3]
        #cast naar int zzzzz
        page_id=int(page_id)
        page_item_id=int(page_item_id)
        order_nr_new=int(new_sort_var)        
    except:
        redirect(error)   

    page_item1=db(db.page_item.id==page_item_id).select().first() or redirect(error)
    order_nr_old=page_item1.order_nr
    
    
    if(order_nr_new > order_nr_old):
        #move down        
        #regel alle nummers die moeten veranderen
        updateOrderNrs = db((db.page_item.order_nr > order_nr_old) & (db.page_item.order_nr <= order_nr_new) & (db.page_item.page==page_id)).select(orderby=db.page_item.order_nr)        
        #zet het order_nr dat verplaatst wordt op 0
        db((db.page_item.order_nr == order_nr_old) & (db.page_item.page==page_id)).update(order_nr = 0)
        #tempNr voor het toewijzen aan order_nr
        tempNr = int(order_nr_old)
        for page_item in updateOrderNrs:
            db(db.page_item.id == page_item.id).update(order_nr = tempNr)
            tempNr += 1
        #geef het verschoven record de juiste waarde
        db((db.page_item.order_nr == 0) & (db.page_item.page==page_id)).update(order_nr = order_nr_new)
        message = 'moved down'
    else:
        #move up        
        #regel alle nummers die moeten veranderen
        updateOrderNrs = db((db.page_item.order_nr < order_nr_old) & (db.page_item.order_nr >= order_nr_new) & (db.page_item.page==page_id)).select(orderby=db.page_item.order_nr)        
        #zet het order_nr dat verplaatst wordt op 0
        db((db.page_item.order_nr == order_nr_old) & (db.page_item.page==page_id)).update(order_nr = 0)
        #tempNr voor het toewijzen aan order_nr
        tempNr = int(order_nr_new) + 1
        for page_item in updateOrderNrs:
            db(db.page_item.id == page_item.id).update(order_nr = tempNr)
            tempNr += 1
        #geef het verschoven record de juiste waarde
        db((db.page_item.order_nr == 0) & (db.page_item.page==page_id)).update(order_nr = order_nr_new)
        message = 'moved up'
    
    redirect(URL('showEditable/%s' % page_id))
    
@auth.requires_membership('admins')
def resetOrderNr():
    try:
        page_id=int(request.args(0))     
    except:
        redirect(error)
    for i in range (1,6):
        db((db.page_item.id == i) & (db.page_item.page==page_id)).update(order_nr = i)
    message = 'reset'
    redirect(URL('showEditable/%s' % page_id))
    return dict(message=message)

@auth.requires_membership('admins')
def editMarkmin():
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_text[item_id] or redirect(error)
        form=SQLFORM(db.page_text,item,formstyle='table2cols')
    else: form=SQLFORM(db.page_text,formstyle='table2cols')
    form.vars.type='markmin'
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_text).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_text',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('text'))

@auth.requires_membership('admins')
def editHtml():
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_text[item_id] or redirect(error)
        form=SQLFORM(db.page_text,item,formstyle='table2cols')
    else: form=SQLFORM(db.page_text,formstyle='table2cols')
    form.vars.type='html'
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_text).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_text',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('text'))

@auth.requires_membership('admins')
def edit():
    """Implements editing of page title and url"""
    dbtable = db.page          #uploads table name
    page_id=int(request.args(0))
    page=db.page[page_id] or redirect(error)
    form=SQLFORM(db.page,page)
    if form.process().accepted:
        #makeThumbnail(dbtable,form.vars.id,(134,134)) #Thumbnail not used in this project
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('Editing the page itself'))

@auth.requires_membership('admins')
def editText():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_text[item_id] or redirect(error)
        form=SQLFORM(db.page_text,item)
    else: form=SQLFORM(db.page_text)
    form.vars.type='textarea'
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_text).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_text',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('Plain text'))

@auth.requires_membership('admins')
def editLink():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_link[item_id] or redirect(error)
        form=SQLFORM(db.page_link,item)
    else: form=SQLFORM(db.page_link)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_link).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_link',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('link'))

@auth.requires_membership('admins')
def editFAQ():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_faq[item_id] or redirect(error)
        form=SQLFORM(db.page_faq,item)
    else: form=SQLFORM(db.page_faq)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_faq).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_faq',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('faq'))

@auth.requires_membership('admins')
def editDealer():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_dealer[item_id] or redirect(error)
        form=SQLFORM(db.page_dealer,item)
    else: form=SQLFORM(db.page_dealer)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_dealer).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_dealer',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('dealer'))

@auth.requires_membership('admins')
def editImage():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_image[item_id] or redirect(error)
        form=SQLFORM(db.page_image,item)
    else: form=SQLFORM(db.page_image)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_image).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_image',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('image'))

def editForm():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_form[item_id] or redirect(error)
        form=SQLFORM(db.page_form,item)
    else: form=SQLFORM(db.page_form)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_form).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_form',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('form'))

@auth.requires_membership('admins')
def editFile():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_file[item_id] or redirect(error)
        form=SQLFORM(db.page_file,item)
    else: form=SQLFORM(db.page_file)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_file).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_file',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('file'))

@auth.requires_membership('admins')
def editPicasa():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_picasa[item_id] or redirect(error)
        form=SQLFORM(db.page_picasa,item)
    else: form=SQLFORM(db.page_picasa)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_picasa).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_picasa',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('picasa'))

@auth.requires_membership('admins')
def editYoutube():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_youtube[item_id] or redirect(error)
        form=SQLFORM(db.page_youtube,item)
    else: form=SQLFORM(db.page_youtube)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_youtube).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_youtube',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('youtube'))

@auth.requires_membership('admins')
def editFacebook():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_facebook[item_id] or redirect(error)
        form=SQLFORM(db.page_facebook,item)
    else: form=SQLFORM(db.page_facebook)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_facebook).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_facebook',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('facebook'))

@auth.requires_membership('admins')
def editTwitter():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_twitter[item_id] or redirect(error)
        form=SQLFORM(db.page_twitter,item)
    else: form=SQLFORM(db.page_twitter)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_twitter).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_twitter',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('twitter'))

@auth.requires_membership('admins')
def editSlider():
    response.view='page/edit.html'
    try:
        page_id, item_id = request.args[:2]
    except:
        redirect(error)    
    page=db.page[page_id] or redirect(error)
    if item_id!="0": 
        item=db.page_slider[item_id] or redirect(error)
        form=SQLFORM(db.page_slider,item)
    else: form=SQLFORM(db.page_slider)
    if form.process().accepted:
        if item_id=="0":
            last=db(db.page_slider).select().last()
            maxPageItem=db(db.page_item.page==page_id).count()
            db.page_item.insert(page=page_id,record_id=last.id,tablename='page_slider',order_nr=maxPageItem+1)
        redirect(URL('showEditable/%s' % page_id))
    return dict(form=form, page=page, subtitle=T('slider'))


@auth.requires_membership('admins')
def movePage():
    #request 1 should be ID or URL_name
    
    if request.args(1):
        #request 2 should be new parent
        page_id=request.args(0)
        page_parent=request.args(1)
        my_page=db(db.page.id==page_id).select().first() or redirect(error)
        my_url=my_page.url
        new_parent=db(db.page.id==page_parent).select().first()
        if new_parent: new_parent=new_parent.id
        else: new_parent=0

        tempNr = int(my_page.order_nr)
        updateOrderNrs = db((db.page.parent==my_page.parent) & (db.page.order_nr > my_page.order_nr)).select(orderby=db.page.order_nr)
        db(db.page.id==my_page.id).update(order_nr = 0)
        for page in updateOrderNrs:
            db(db.page.id == page.id).update(order_nr = tempNr)
            tempNr += 1
        
        highestOrderNr=db(db.page.parent==new_parent).select(orderby=db.page.order_nr).last()
        if highestOrderNr: highestOrderNr=int(highestOrderNr.order_nr + 1)
        else: highestOrderNr=1
        
        row = db(db.page.id == page_id).select().first()
        row.update_record(parent=page_parent, order_nr=highestOrderNr)
                
        redirect(URL('show',args=(my_url)))
   
    try:
        page_id=int(request.args(0))
        my_page=db.page[page_id] or redirect(error)
    except:
        my_page=db(db.page.url==request.args(0)).select().first() or redirect(error)
        page_id=page.id
        
    pages=db(db.page).select(orderby=db.page.parent) or redirect(error)
    return dict(my_page=my_page, pages=pages)

def showPicasa():
    gd_photo_client = gdata.photos.service.PhotosService()
    #id = request.args(0) or 'error'
    userID=request.args(0) or 'error'
    albumID=request.args(1) or 'error'
    if userID and albumID:
        try:
            photos = gd_photo_client.GetFeed('/data/feed/base/user/%s/albumid/%s?kind=photo' % (userID, albumID))
        except:
            redirect(error_no_linked_content)
    return dict(photos=photos.entry)
 
#@cache(request.env.path_info, time_expire=1, cache_model=cache.ram)     
def show():
    import time
    t = time.ctime()
    
    #request 1 should be ID or URL_name
    try:
        page_id=int(request.args(0))
        page=db.page[page_id] or redirect(error)
    except:
        page=db(db.page.url==request.args(0)).select().first() or redirect(error)
        page_id=page.id
    page_children=db(db.page.parent==page_id).select(orderby=db.page.order_nr)   
    page_items = db((db.page_item.page==page.id) & (db.page_item.tablename!='page_form')).select(orderby=db.page_item.order_nr)

    is_admin=auth.has_membership('admins')

    content=[]
    for page_item in page_items:
        if page_item.tablename=='page_text':
            temp=db.page_text[page_item.record_id] or redirect(error_no_text)
            content.append(temp)
        elif page_item.tablename=='page_image':
            temp=db.page_image[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_link':
            temp=db.page_link[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_faq':
            temp=db.page_faq[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)   
        elif page_item.tablename=='page_dealer':
            temp=db.page_dealer[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)  
        elif page_item.tablename=='page_file':
            temp=db.page_file[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_picasa':
            temp=db.page_picasa[page_item.record_id] or redirect(error_no_linked_content)
            gd_photo_client = gdata.photos.service.PhotosService()
            #id = request.args(0) or 'error'
            userID=temp.userid
            albumID=temp.albumid
            if userID and albumID:
                try:
                    photos = gd_photo_client.GetFeed('/data/feed/base/user/%s/albumid/%s?kind=photo' % (userID, albumID))
                    content.append(photos.entry)
                except:
                    redirect(error_no_linked_content)
        elif page_item.tablename=='page_youtube':
            temp=db.page_youtube[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_facebook':
            temp=db.page_facebook[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_twitter':
            temp=db.page_twitter[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_slider':
            temp=db.page_slider[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
    return dict(page=page, page_items=page_items, content=content, page_children=page_children, is_admin=is_admin)

@auth.requires_membership('admins')
def showEditable():
    #request 1 should be ID or URL_name
    try:
        page_id=int(request.args(0))
        page=db.page[page_id] or redirect(error)
    except:
        page=db(db.page.url==request.args(0)).select().first() or redirect(error)
        page_id=page.id
    page_children=db(db.page.parent==page_id).select(orderby=db.page.order_nr)   
    form=SQLFORM.factory(db.page)
    if form.accepts(request.vars):
        #makeThumbnail(dbtable,form.vars.id,(134,134))
        form.vars.parent=page_id
        maxPage=db(db.page.parent==page.parent).count()
        form.vars.order_nr=maxPage+1
        form.vars.language=T.accepted_language
        db.page.insert(**db.page._filter_fields(form.vars))
        redirect(URL('showEditable/%s' % page_id))
    page_items = db(db.page_item.page==page.id).select(orderby=db.page_item.order_nr)
    content=[]
    for page_item in page_items:
        if page_item.tablename=='page_text':
            temp=db.page_text[page_item.record_id] or redirect(error_no_text)
            content.append(temp)
        elif page_item.tablename=='page_image':
            temp=db.page_image[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_link':
            temp=db.page_link[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_faq':
            temp=db.page_faq[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp) 
        elif page_item.tablename=='page_dealer':
            temp=db.page_dealer[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp) 
        elif page_item.tablename=='page_file':
            temp=db.page_file[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_picasa':
            temp=db.page_picasa[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_youtube':
            temp=db.page_youtube[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_facebook':
            temp=db.page_facebook[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_twitter':
            temp=db.page_twitter[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_slider':
            temp=db.page_slider[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)
        elif page_item.tablename=='page_form':
            temp=db.page_form[page_item.record_id] or redirect(error_no_linked_content)
            content.append(temp)            
    return dict(page=page, page_items=page_items, page_children=page_children,
                content=content, form=form)

def getAlbums():
    userID= request.args(0)
    lstAlbums = []
    if userID:
        try:
            albums = gd_photo_client.GetUserFeed(user=userID)
            for album in albums.entry:
                entry=A(IMG(_src=album.media.thumbnail[0].url, _alt=album.title.text), _href=URL('getPhotos/%s/%s' % (userID, album.gphoto_id.text))) 
                lstAlbums.append(entry)
        except:
            redirect(URL('index'))
    else:
        redirect(URL('index'))
    return dict(lstAlbums=DIV(*[lstAlbums]))

def getPhotos():
    userID=request.args(0)
    albumID=request.args(1)
    lstPhotos =[]
    if userID and albumID:
        try:
            photos = gd_photo_client.GetFeed('/data/feed/base/user/%s/albumid/%s?kind=photo' % (userID, albumID))
            for photo in photos.entry:
                entry=A(IMG(_src=photo.media.content[0].url, _alt=photo.title.text, _width='320', _height='258')) 
                lstPhotos.append(entry)
        except:
            redirect(URL('index'))
    else:
        redirect(URL('index'))
    return dict(lstPhotos=DIV(*[lstPhotos]))

def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())

def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)

@auth.requires_membership('admins')
def export():
    db.export_to_csv_file(open('somefile.csv', 'wb'))

def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()

def data():
    """
    http://..../[app]/default/data/tables
    http://..../[app]/default/data/create/[table]
    http://..../[app]/default/data/read/[table]/[id]
    http://..../[app]/default/data/update/[table]/[id]
    http://..../[app]/default/data/delete/[table]/[id[
    http://..../[app]/default/data/select/[table]
    http://..../[app]/default/data/search/[table]
    but URLs bust be signed, i.e. linked with
      A('table',_href=URL('data/tables',user_signature=True))
    or with the signed load operator
      LOAD('default','data.load',args='tables',ajax=True,user_signature=True)
    """
    return dict(form=crud())